#!/usr/bin/python
import yeast_util
import math
import sys
import os
import time

print "Parsing strains and values kicked off %s" %time.ctime()
if (len(sys.argv) != 3):
        print 'Usage is py2.6 parse_values_kruglyak.py /local/dudley/omics/KruglyakGenewisePhenoProteomics.NEW.transposed.csv dataset_label'
        sys.exit(1)

infile = open(sys.argv[1])
dataset_label = sys.argv[2]
schema = "omics"
feature_table = schema + "." + dataset_label + "_features"
strains_table = schema + "." + dataset_label + "_strains"

#infile = open('/local/dudley/omics/KruglyakGenewisePhenoProteomics.NEW.transposed.csv');
feature_helper = {}
feature_helper["IMP2"] = "C:GENO:IMP2:chrIX:53981:55021:-"
feature_helper["AAP1"] = "C:GENO:AAP1:chrVIII:198740:201310:-"
features_hash = {}
fshout = open('load_strain_values_' + dataset_label + '.sh','w')
outfile = open('./strain_values_out_' + dataset_label + '.sql','w')
#fshout = open('loadKruglyakValuesSql_pv.sh','w')
#outfile = open('/local/dudley/omics/KruglyakValuesOut_pv.sql','w')
linec = 0
insertStrainsSql = ''
for line in infile:
	line = line.strip()
	if (linec == 0):
		strains = line.replace('\t', ':')
		strainsplt = strains.split(':')
		strainStr = ""
		for ss in strainsplt:
			#print ss
			ypgkey = yeast_util.getYPGKey(ss)
			if (ypgkey == None):
				ypgkey = ""
			strainDesc = ypgkey + '_' + ss
			strainStr = strainStr + strainDesc + ":"
		insertStrainsSql= "insert into %s values ('%s');\n" %(strains_table, strainStr[0:len(strainStr)-1])
		outfile.write(insertStrainsSql)
	else:
		valuesArray = []
		tokens = line.split('\t')
		alias = tokens[0]
		if (alias.find('PHENO') != -1):
                	alias = yeast_util.transPhenoFeature(tokens[0])
		if (alias.find("IMP2") != -1):
			alias = yeast_util.transGeneFeature("IMP2")
		if (alias.find("AAP1") != -1):
			alias = yeast_util.transGeneFeature("AAP1")		
		values = ":".join(tokens[1:len(tokens)-1]) 
		for v in tokens[1:len(tokens)-1]:
			if (v != 'NA' and v != 'A' and v != 'B'):
				valuesArray.append(float(v))
		if (alias.find("PROT") != -1):
			#log protein values
			values = ''
			valuesArray = []
			for v in tokens[1:len(tokens)-1]:
				if (v != 'NA'):
					valuesArray.append(math.log(float(v)))
					values = values + str(math.log(float(v))) + ":"
				else:
					values = values + v + ":"
			values = values[0:len(values)-1]
		mean = 0.0
		if (len(valuesArray) > 1):
			mean = sum(valuesArray)/len(valuesArray)		
		outfile.write("update %s set strain_values = '%s', strain_values_mean = %f where alias = '%s';\n" %(feature_table, values, mean,alias))  
	linec = linec + 1
print insertStrainsSql
infile.close()
outfile.close()
fshout.write("#!/bin/bash\n")
#fshout.write("mysql --user=root --database=omics<<EOFMYSQL\n")
fshout.write('mysql -ududley_omics -pdud1ey < ' + outfile.name + '\n')
# '/local/dudley/omics/KruglyakValuesOut_pv.sql\n')

#fshout.write("load data local infile '/local/dudley/omics/KruglyakFeaturesOut.tsv' replace INTO TABLE kruglyak_features " + " fields terminated by '\\t' LINES TERMINATED BY '\\n';")
#fshout.write("\nEOFMYSQL")
fshout.close()
print "done parsing %s, running sh %s" %(time.ctime(), fshout.name)
os.system("sh " + fshout.name)
